from django.conf import settings
from django.core.files.storage import Storage
from fdfs_client.client import Fdfs_client


class FastDFSStorage(Storage):
    def __init__(self, base_url=None, client_conf=None):
        """
            初始化
            :param base_url: 用于构造图片完整路径使用，图片服务器的域名
            :param client_conf: FastDFS客户端配置文件的路径
        """
        if base_url is None:
            base_url = settings.FDFS_URL
        self.base_url = base_url

        if client_conf is None:
            client_conf = settings.FDFS_CLIENT_CONF
        self.client_conf = client_conf

    def _open(self, name, mode='rb'):
        """
        用不到打开文件，所以省略
        """
        pass

    def _save(self, name, content):
        """
            在FastDFS中保存文件
            :param name: 传入的文件名
            :param content: 文件内容
            :return: 保存到数据库中的FastDFS的文件名
        """
        #创建Fdfs_client对象,指明配置文件
        client = Fdfs_client("meiduo_mall/utils/fastdfs/client.conf")

        ret = client.upload_by_buffer(content.read())
        """
        {'Group name': 'group1',
         'Local file name': '/home/python/Desktop/timg.jpg',
         'Remote file_id': 'group1/M00/00/00/wKgXi1xjyJiAEK1IAAClbSKkkvI463.jpg',
         'Status': 'Upload successed.',
         'Storage IP': '192.168.23.139',
         'Uploaded size': '41.00KB'}

        """

        if ret.get("Status") != 'Upload successed.':
            raise Exception("upload file failed")

        #  'group1/M00/00/00/wKgXi1xjyJiAEK1IAAClbSKkkvI463.jpg'
        file_name = ret.get("Remote file_id")

        return file_name


    def url(self, name):
        return self.base_url + name

    def exists(self, name):
        return False





